<template>
  <div class="wrap">
    <el-popover
      ref="popover4"
      placement="bottom"
      @show="popoverShow"
      @after-leave="popoverHide"
      width="240"
      trigger="click">
      <m7-tree
        class="el-tree1"
        ref="tree"
        height="280"
        node-key="_id"
        :show-checkbox="true"
        :data="treeData"
        accordion
        :default-expanded-keys="treeData[0] ? [treeData[0]._id]: []"
        :default-expand-all="false"
        :render-content="renderContent"
        @check="save"
        :filter-node-method="filterNode">
      </m7-tree>
    </el-popover>
    <div>
      <div class="el-select el-select--mini" v-popover:popover4 @click="inputClick">
        <div class="el-select__tags tag-input">
          <div v-if="leaf.length" style="display: flex">
            <el-tag
              size="mini"
              type="info"
              @close="deleteAgent(leaf[0])"
              closable>
              <span class="tag-max">{{tagName}}</span>
            </el-tag><el-tag type="info" size="mini" v-if="leaf.length > 1">+{{leaf.length - 1}}</el-tag>
          </div>
          <input type="text"
                 autocomplete="off"
                 debounce="0"
                 class="el-select__input is-mini"
                 ref="input" v-model="value">
        </div>
        <div class="el-input el-input--mini">
          <input type="text" autocomplete="off" :placeholder="placeholder" readonly="readonly" class="el-input__inner" style="height: 28px;">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import m7Tree from '../../ui-modules/tree/src/tree'
  export default {
    name: 'mulitTree',
    data () {
      return {
        value: '',
        leaf: [],
        branch: []
      }
    },
    props: {
      treeData: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    components: {
      m7Tree
    },
    computed: {
      placeholder () {
        return this.value || this.leaf.length ? '' : this.$t('public.pleasePick')
      },
      tagName () {
        let agents = this.$agentsMap()
        if (this.leaf.length) {
          // split，不同技能组有相同坐席处理
          let current = agents[this.leaf[0].split(':')[0]] || {}
          return current.displayName
        }
        return ''
      }
    },
    watch: {
      value (val) {
        this.$refs.tree.filter(val)
      }
    },
    methods: {
      inputClick () {
        this.$refs.input.focus()
      },
      popoverShow () {
        this.setCheckedKeys()
      },
      popoverHide () {
        this.$nextTick(() => {
          this.value = ''
        })
      },
      save (data, checked) {
        if (data) {
          this.value = ''
          this.$refs.input.focus()
        }
        let agents = this.$agentsMap() || {}
        // 把树分成树支和树叶
        this.branch = []
        this.leaf = []
        checked.checkedKeys.forEach((item) => {
          // split，不同技能组有相同坐席处理
          if (agents[item.split(':')[0]]) {
            this.leaf.push(item)
          } else {
            this.branch.push(item)
          }
        })
        if (this.leaf.length === 0 && this.branch.length === 0) {
          // 什么都不不选，相当于全选
          this.$emit('change', {branch: [], leaf: this.getLeafNode()})
        } else {
          this.$emit('change', {branch: this.branch, leaf: this.leaf})
        }
      },
      getLeafNodeItem (treeData, arr) {
        for (let i = 0; i < treeData.length; i++) {
          let item = treeData[i]
          if (item.type === 'agent') {
            arr.push(item._id)
          }
          if (item.children && item.children.length) {
            this.getLeafNodeItem(item.children, arr)
          }
        }
      },
      getLeafNode () {
        let arr = []
        this.getLeafNodeItem(this.treeData, arr)
        return arr
      },
      renderContent (h, { node, data, store }) {
        let agentFlag = false
        if ((node.childNodes.length) === 0 && (node.isLeaf === true)) {
          agentFlag = true
        }
        if (node.checked) {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ]),
              h('span', {
                domProps: {
                  innerHTML: ' (已选)'
                },
                style: {
                  color: '#459ae9'
                },
                class: {
                  readed: true
                }
              }, [
              ])
            ])
          )
        } else {
          return (
            h('span', {
              class: {
                myheader: true,
                floatfl: agentFlag
              }
            }, [
              h('span', {
                class: {
                  name: true
                },
                domProps: {
                  innerHTML: data.label
                }
              }, [
              ])
            ])
          )
        }
      },
      resetAgent () {
        this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.reset()
      },
      setCheckedKeys () {
        this.$refs.tree.setCheckedKeys(this.leaf || [])
        this.$refs.tree.reset()
      },
      deleteAgent (key) {
        this.$refs.tree.setChecked(key, false)
        this.leaf.shift()
        this.$refs.tree.$emit('check', null, {checkedKeys: this.leaf})
      },
      filterNode (value, data) {
        if (!value) return true
        return data.type === 'agent' && (data.label.indexOf(value) !== -1 || data.pinyin.indexOf(value) !== -1)
      }
    },
    mounted () {
    }
  }
</script>

<style scoped lang="stylus">
  @import '../../../assets/common.styl'
  .wrap
    display inline-block
  .el-select
    width 220px
    box-sizing border-box
  .tag-input
    width 200px
    display flex
    flex-direction row
    flex-wrap nowrap
    justify-content left
  .tag-max
    max-width 60px
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .el-tree1
    padding-bottom 5px
    max-height 280px
    overflow auto
    border none
</style>
